import { Tree, Checkbox, Button, message } from 'antd';
import React, { useState, useEffect } from 'react';
import http from '@/utils/axios';

let dataJson: any = null
const App = () => {
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [treeData, setTreeData] = useState([]);
  const [featData, setFeatData] = useState([]);
  const [requestData, setRequestData] = useState([]);


  const tranListToTreeData = (list = [], id = ""): any[] => {
    return list.filter(e => e.ParentID === id).map(e => {
      return {
        title: e.Title,
        key: e.ID,
        children: tranListToTreeData(list, e.ID),
        ...e
      }
    })
  }
  const query = async () => {
    await http.get('/api/TEST/Data.json').then(res => {
      dataJson = res.data.Data
      const data = tranListToTreeData(res.data.Data)
      // 扁平化结构转tree结构
      setTreeData(data)
    })
    http.get('/api/TEST/RequestData.json',).then(res => {
      const menuCheckData = res.data.map(e => {
        if (e.CheckState === 1) {
          return e.ID
        }
        else {
          return null
        }
      }).filter(e => e !== null)
      console.log('menuCheckData', menuCheckData)
      const funList = res.data.map(e => {
        return e.FuncList
      }).flat(Infinity).filter(e1 => e1.Checked).map(e2 => e2.ID)
      setFeatData(funList)
      setCheckedKeys(menuCheckData)
      setRequestData(res.data)
    })
  }

  useEffect(() => {
    query()
  }, []);

  const onExpand = (expandedKeysValue: any) => {
    console.log('onExpand', expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: any) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: any, info: any) => {
    // 阻止默认事件流
    info.nativeEvent.preventDefault()
    setSelectedKeys(selectedKeysValue);
  };

  return (
    <div>
      <Tree
        style={{ width: '100%' }}
        checkable
        titleRender={(e: any) =>
          <div style={{
            display: "flex",
            justifyContent: "space-between",

          }}>
            <div>{e.title}</div>
            <div style={{
              marginLeft: 100,
              position: "relative",
              zIndex: 99
            }}>
              {e?.Ent?.FuncList.map(e1 => {
                return <Checkbox
                  autoFocus
                  onClick={() => {
                    if (featData.includes(e1.ID)) {
                      setFeatData((d) => {
                        return d.filter(e => e !== e1.ID)
                      })
                    }
                    else {
                      setFeatData((d) => {
                        return [...d, e1.ID]
                      })
                    }
                  }}
                  checked={featData.includes(e1.ID)}
                >
                  {e1.Title}
                </Checkbox>
              })}
            </div>
          </div>
        }
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        onSelect={onSelect}
        selectedKeys={selectedKeys}
        treeData={treeData}
      />
      <div style={{
        padding: "20px",
        marginTop: "20px",
        backgroundColor: "#fff",
        textAlign: "right"
      }}>
        <Button type='primary' onClick={() => {
          console.log('dataJson', dataJson)
          let JsonRequestData = JSON.parse(JSON.stringify(dataJson)) || []
          JsonRequestData = JsonRequestData.map(e => {
            return {
              ID: e.ID,
              CheckState: checkedKeys.includes(e.ID) ? 1 : 0,
              FuncList: e.Ent.FuncList.map(e1 => {
                return {
                  ID: e1.ID,
                  Checked: featData.includes(e1.ID)
                }
              })
            }
          })
          console.log('JsonRequestData', JsonRequestData)

          http.post('/api/TEST/RequestData.json', {
            ...JsonRequestData
          }).then(res => {
            if (res.data.Status === 1) {
              message.success('保存成功')
              query()
            }
          }).catch(err => {
            message.error('保存失败,服务器异常')
          })

        }}>保存</Button>
      </div >
    </div >
  );
};

export default App;